/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.forecast.service;

import com.fzhucc.modules.forecast.domain.RaceForecast;
import com.fzhucc.modules.forecast.domain.dto.ForecastDto;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.forecast.repository.RaceForecastRepository;
import com.fzhucc.modules.forecast.domain.dto.RaceForecastDto;
import com.fzhucc.modules.forecast.domain.dto.RaceForecastQueryCriteria;
import com.fzhucc.modules.forecast.service.mapstruct.RaceForecastMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-08-11
 **/
@Service
@RequiredArgsConstructor
public class RaceForecastService {

    private final RaceForecastRepository raceForecastRepository;
    private final RaceForecastMapper raceForecastMapper;

    public Map<String, Object> queryAll(RaceForecastQueryCriteria criteria, Pageable pageable) {
        Page<RaceForecast> page = raceForecastRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(raceForecastMapper::toDto));
    }

    public List<RaceForecastDto> queryAll(RaceForecastQueryCriteria criteria) {
        return raceForecastMapper.toDto(raceForecastRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public RaceForecastDto findById(Integer id) {
        RaceForecast raceForecast = raceForecastRepository.findById(id).orElseGet(RaceForecast::new);
        ValidationUtil.isNull(raceForecast.getId(), "RaceForecast", "id", id);
        return raceForecastMapper.toDto(raceForecast);
    }

    @Transactional(rollbackFor = Exception.class)
    public RaceForecastDto create(RaceForecast resources) {
        return raceForecastMapper.toDto(raceForecastRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(RaceForecast resources) {
        RaceForecast raceForecast = raceForecastRepository.findById(resources.getId()).orElseGet(RaceForecast::new);
        ValidationUtil.isNull(raceForecast.getId(), "RaceForecast", "id", resources.getId());
        raceForecast.copy(resources);
        raceForecastRepository.save(raceForecast);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            raceForecastRepository.deleteById(id);
        }
    }

    public RaceForecastDto forecast(ForecastDto forecastDto) {
        RaceForecast raceForecast = new RaceForecast();
        raceForecast.setCreatetime(new Timestamp(new Date().getTime()));
        raceForecast.setName(forecastDto.getName());
        raceForecast.setPhone(forecastDto.getPhone());
        raceForecast.setPname(forecastDto.getPname());
        raceForecast.setGroup(forecastDto.getGroup());
        raceForecast.setCompany(forecastDto.getCompany());
        raceForecast.setIsCounselling(forecastDto.getIsCounselling());
        RaceForecast saveRaceForecast = raceForecastRepository.save(raceForecast);
        try {
            //同时注册到福州大赛系统
            reigstRace(saveRaceForecast.getName(), saveRaceForecast.getPhone());
        } catch (Exception e) {
        }
        return raceForecastMapper.toDto(saveRaceForecast);
    }

    public void reigstRace(String realName, String phone) {
        String url = "https://www.fzzgsc.com/api/sys/user/batchRegister";
        String jsonStr = "{\n" +
                "    \"list\": [\n" +
                "        {\n" +
                "            \"realName\": \""+realName+"\",\n" +
                "            \"phone\": \""+phone+"\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        HttpUtils2.post(url, jsonStr);
    }

    public void download(List<RaceForecastDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RaceForecastDto raceForecast : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("姓名", raceForecast.getName());
            map.put("手机号", raceForecast.getPhone());
            map.put("项目名称", raceForecast.getPname());
            map.put("提交时间", raceForecast.getCreatetime());
            map.put("组别", raceForecast.getGroup());
            map.put("公司", raceForecast.getCompany());
            map.put("是否需要辅导", raceForecast.getIsCounselling());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}